package com.xxl.filter;


import com.xxl.dto.UserDto;
import com.xxl.service.UserService;
import com.xxl.util.ConstantField;
import com.xxl.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;

/**
 * 身份认证和权限认证的祖宗
 * 判断用户是免密登录的还是session登录的
 *
 * @author xxl
 * @date 2023/4/4
 */
@Slf4j
public class AuthorizationAndAuthenticationBaseFilter implements Filter {
    protected UserDto userDto = null;
    @Resource
    UserService service;
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest rep = (HttpServletRequest) request;
        //如果不为空表示没使用记住我功能 为false ，使用了记住我功能就是true
        if (rep.getSession().getAttribute(ConstantField.USER_COOKIE_NAME) != null) {
            doSessionAuthentication(rep);
        } else {
            doCookieAuthentication(rep);
        }
        log.error("顶类UserDto"+userDto.toString());
    }

    /**
     * 通过cookie拿到用户信息
     */
    protected void doCookieAuthentication(HttpServletRequest request) {
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals(ConstantField.USER_COOKIE_NAME)) {
                //存在token里面的
                if (JwtUtil.parseJwt(cookie.getValue()) instanceof HashMap<?,?> map) {
                    String username = (String) map.get("username");
                    String password = (String) map.get("password");
                    userDto = service.login(username,password);
                }
            }
        }
    }

    /**
     * 通过session拿到用户信息
     */
    protected void doSessionAuthentication(HttpServletRequest request) {
        String token = (String) request.getSession().getAttribute(ConstantField.USER_COOKIE_NAME);
        //存在token里面的
        if (JwtUtil.parseJwt(token) instanceof HashMap<?,?> map) {
             String username = (String) map.get("username");
             String password = (String) map.get("password");
            userDto = service.login(username,password);
        }
    }

}
